<?php
/**
 * Created by jinqiang on 2024/7/3 10:51.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\SsyProcessingListDetailsTable;
use App\Http\Models\Mysql\SsySizeRuleTable;

class RfidRepository
{
    /**
     * 生成Rfid唯一码
     * 生产规则
     * SHF151937 K  YL  XXL
     * S=1
     * HF=1
     * 151937=151937
     * 复刻=K=1
     * YL=06
     * XXL=03
     * 流水号=000000100
     * 密码=SHISANYU(每个月变)
     * 1  1 151937 01 06 03 000000100  CNC(2位)
     * 密码规则：A=JIEQU (HEX(MD5（SHF151937 K  YL  XXL+SHISANYU）),2)
     */
    public static function createNumber($processingCode, $typeNo, $skuCode, $typeName, $colorCode, $sizeCode, $num, $factoryName, $factoryId, $yichu = true)
    {
        //获取当前sku的最大序列号
        $rfidDetail = (new SsyProcessingListDetailsTable())->where('sku_code', $skuCode)->orderBy('s_number', 'desc')->first();
        $maxSNumber = 0;
        if(!empty($rfidDetail)){
            $maxSNumber = $rfidDetail->s_number;
        }
        //第1位
        $sizeRuleObj = (new SsySizeRuleTable())->where('type', 3)->where('s_key', substr($typeNo,0,1))->first();
        if(empty($sizeRuleObj)){
            return ['code' => -1, 'msg' => '生成失败：编码第1位缺失品牌类型'];
        }
        $rfid_1 = $sizeRuleObj->s_val;
        //第2位
        $sizeRuleObj = (new SsySizeRuleTable())->where('type', 4)->where('s_key', substr($typeNo,1,2))->first();
        if(empty($sizeRuleObj)){
            return ['code' => -1, 'msg' => '生成失败：编码第2位缺失形制类型'];
        }
        $rfid_2 = $sizeRuleObj->s_val;
        //第3位
        $typeNoSx = substr($typeNo,3);
        $typeNoSxEg = strtoupper(preg_replace('/(\d+)/','', $typeNoSx));
        $fk = '0';
        if(!empty($typeNoSxEg)){
            $eg = ['DK' => '2', 'K' => '1', 'TK' => '3'];
            $fk = $eg[$typeNoSxEg] ?? '';
            if(empty($fk)){
                return ['code' => -1, 'msg' => '生成失败：款号中后缀出现未知字母'];
            }
        }
        $typeNoSxNum = preg_replace('/([a-zA-Z]+)/','', $typeNoSx);
        $typeNoSxNumLen = strlen($typeNoSxNum);
        if($typeNoSxNumLen > 7 || $typeNoSxNumLen < 5){
            return ['code' => -1, 'msg' => '生成失败：款号位数错误'];
        }else{
            $typeNoSxNum = str_pad($typeNoSxNum,7,"0",STR_PAD_RIGHT);
        }
        //颜色码
        $rfid_3 = $typeNoSxNum.$fk."00";
        if(!empty($colorCode)){
            $sizeRuleObj = (new SsySizeRuleTable())->where('type', 2)->where('s_key', $colorCode)->first();
            if(empty($sizeRuleObj)){
                return ['code' => -1, 'msg' => '生成失败：颜色编码错误'];
            }
            $rfid_3 = $typeNoSxNum.$fk.$sizeRuleObj->s_val;
        }
        //尺寸码
        if(empty($sizeCode)){
            return ['code' => -1, 'msg' => '生成失败：尺码不能为空'];
        }
        $rfid_4 = "00";
        $sizeRuleObj = (new SsySizeRuleTable())->where('type', 1)->where('s_key', $sizeCode)->first();
        if(!empty($sizeRuleObj)){
            $rfid_4 = $sizeRuleObj->s_val;
        }else{
            if(!is_numeric($sizeCode)){
                return ['code' => -1, 'msg' => '生成失败：尺码没有找到值'];
            }
        }
        //获取密码
        $codeStr = $rfid_1.$rfid_2.$rfid_3.$rfid_4;
        $totalNum = $num + ($yichu ? ceil($num * config("scm.overflow")) : 0) + $maxSNumber;
        $index = empty($maxSNumber) ? 1 : $maxSNumber + 1;
        for($i = $index; $i <= $totalNum; $i++){
            $indexNum = str_pad($i,8,"0",STR_PAD_LEFT);
            $number = $codeStr.$indexNum.substr(bin2hex(md5($codeStr.$indexNum)), -2);
            if(strlen($number) != 24){
                return ['code' => -1, 'msg' => '生成失败：生成rfid码长度错误'];
            }
            if(in_array($typeNo, ['STZ117037'])){//山姆线下 SGTIN-96码
                $itemCodeMap = ["120" => '0000', "130" => '0001', "140" => '0002', "150" => '0003'];
                $rfidRes = (new SGTIN96EncoderRepository())->encode(3, 'unit', '697921014', $itemCodeMap[$sizeCode], $i);
                if($rfidRes['code'] !== 0){
                    return $rfidRes;
                }
                $number = $rfidRes['hex'];
            }
            $data = [
                'number' => $number,
                'type_name' => $typeName,
                'processing_code' => $processingCode,
                'type_no' => $typeNo,
                'color_code' => $colorCode,
                'sku_code' => $skuCode,
                'size_code' => $sizeCode,
                'type_status' => $yichu ? 0 : 1,//默认 0 1补码
                's_number' => $i,//序号
                'factory_name' => $factoryName,//工厂名称
                'supplier_id' => $factoryId,//工厂id
                'createtime' => date("Y-m-d H:i:s")
            ];
            $res = (new SsyProcessingListDetailsTable())->createData($data);
            if($res['code'] !== 0){
                return $res;
            }
        }
        return ['code' => 0, 'msg' => 'rfid生成完成'];
    }
}
